import React, { useState, useEffect, useRef } from 'react';
import { TjCollapse, TjDimensionOptions, TjFilter, TjHeader, TjSlideSelect } from '@/tjComponents';
import { connect } from 'umi';
import { useRequestPowerAfterInit } from '@/hooks/useRequestPowerAfterInit';
import type { ProvinceType, StationType } from '@/hooks/useRequestPowerAfterInit';
import { Button, DatePicker, message, Select, Tabs } from 'antd';
import _ from 'lodash';
import TjMarketingUnit from '@/tjComponents/TjMarketingUnit';
import { useForm } from 'antd/lib/form/Form';
import moment from 'moment';
import { HttpCode } from '#/utils/contacts.js';
// @ts-ignore
import { TjTable, TjDimension } from '@/pages/ETrade/components';
import {
  flexibleAggregation,
  getDictionaryStatus,
  listAlgorithm,
  reanalyzeDataAlgorithmSum,
} from './services';
import { buildDictionaryStatusData } from './utils';
import { useSetState } from 'ahooks';
import { SERVER_URL_OBJ } from '@/../config/urlConfig';
import {
  chartsShowValueConfig,
  columns,
  exportHeader,
  exportMerges,
  header,
  operators,
  orderOptions,
} from './helper';
import { features, useTablePipeline } from 'ali-react-table';
import {
  buildDimensionChartData,
  buildDimensionTableData,
  tileTbaleColumn,
  findNodeByIndexPath,
} from '@/utils/buildTableByDimension';
import BoardContent from './components/BoardContent';
import DimensionCharts from './components/DimensionCharts';
import { export_json_to_excel } from '@/utils/fileExport.js';
import type { buildDimensionChartDataType, tileColumnType } from '@/utils/buildTableByDimension';

import './index.less';
import TRDefault from '@/tool/components/TRTheme/TRDefault';

const { RangePicker } = DatePicker;
const initFilterValue = {
  time: () =>
    moment().diff(moment().startOf('month'), 'days') > 1
      ? [moment().startOf('month'), moment()]
      : [
          moment().subtract(1, 'months').startOf('month'),
          moment().subtract(1, 'months').endOf('month'),
        ],
  point: '96',
  tag: '1',
  order: ['交易单元', '日期'],
};

const AIStrategyReview: React.FC<IAIStrategyReviewProps> = (props) => {
  const [form] = useForm();
  const [defaultValues, setDefaultValues] = useSetState<any>({});
  const [req, setReq] = useSetState<any>({
    stationIdList: [],
    strategyType: '1',
  });
  const { initLoading, province, treeData } = useRequestPowerAfterInit(
    `/power/dataPower/common/${props.menuCode}/t_station`,
    (parmas) => {
      const obj = {
        ...initFilterValue,
        stationIdList: parmas.stations.map((v: StationType) => {
          return v.stationId;
        }),
        marketId: parmas.value,
        time: initFilterValue.time(),
        regionCode: parmas.provinceId,
      };
      setCurrentProvinceInfo(parmas);
      setDefaultValues(obj);
      setReq(obj);
    },
    {
      convertResult: '2',
      matchFirst: 0,
    },
  );
  const [currentProvinceInfo, setCurrentProvinceInfo] = useState<ProvinceType>();
  const [algorithmList, setAlgorithmList] = useState<any[]>([]);
  const [dictionaryStatus, setDictionaryStatus] = useState<any[]>([]);
  const [dimensionVal, setDimensionVal] = useState<string[]>(orderOptions.slice(0, 2));
  const [dataSource, setDataSource] = useState<any[]>([]);
  const tileColumn = useRef<tileColumnType[]>([]);
  const [openKeys, setOpenKeys] = useState<string[]>([]);
  const [chartFilterOptions, setChartFilterOptions] = useState<any[]>([]);
  const [chartFilterValus, setChartFilterValus] = useState<buildDimensionChartDataType['valIndex']>(
    [],
  );
  const [currentChartsArr, setCurrentChartsArr] = useState<any[]>([]);
  const [totalData, setTotalData] = useState<any>({});
  const [loading, setLoading] = useState<boolean>(false);
  const [tableSorts, setTableSorts] = useState<any[]>([]);

  const allTableTreeData = useRef<any[]>([]);
  const tableExportData = useRef<any[]>([]);

  const changeMarketId = (val: string) => {
    const item = _.find(province, (n: ProvinceType) => n.value === val);
    if (item) {
      setCurrentProvinceInfo(item);
      form.setFieldsValue({
        stationIdList: item.stations.map((v: StationType) => {
          return v.stationId;
        }),
      });
    }
  };

  const aggregation = () => {
    setReq({ order: dimensionVal });
  };

  const init = () => {
    return Promise.all([listAlgorithm(), getDictionaryStatus()]);
  };

  const getQueryParmas = (data: any) => {
    const { CLIENT_ENV } = process.env;
    let env: string | undefined = CLIENT_ENV;
    if (CLIENT_ENV && CLIENT_ENV === 'dev') {
      env = 'test';
    }
    const host = (SERVER_URL_OBJ as any)[env || 'release'];

    const param: any = {
      menuCode: props.menuCode,
      stationIdList: data.stationIdList,
      point: data.point,
      tag: data.tag,
      algorithm: [data.algorithm],
      reanalyzeDataType: data.tag === '1' ? 'CS' : 'JS',
      dataTimeOrderType: data.point === '24' ? 'TWENTY_FOUR' : 'NINETY_SIX',
      regionCode: currentProvinceInfo?.provinceId, // 检查
      strategyType: req.strategyType,
    };

    if (data.issueStatus) {
      param.issueStatus = data.issueStatus.split(',');
    }

    if (data.time && data.time.length > 0) {
      param.startDate = moment(data.time[0]).format('YYYY-MM-DD');
      param.endDate = moment(data.time[1]).format('YYYY-MM-DD');
      // param.startDate = '2024-11-12';
      // param.endDate = ' 2024-11-19';
    }

    return {
      cacheable: true,
      needTotal: true,
      operators: operators,
      order: req.order,
      url: `${host}/reanalyze/aiStrategy/reanalyzeDataAlgorithm`,
      param: param,
    };
  };

  const query = () => {
    const newReq = getQueryParmas(req);
    setLoading(true);
    const algorithmSumParams = {
      ...newReq.param,
    };
    delete algorithmSumParams.strategyType;

    reanalyzeDataAlgorithmSum(algorithmSumParams).then((res: any) => {
      if (res.statusCode === HttpCode.SUCCESS) {
        const data = {
          strategy: { ...res.data.策略版 },
          smooth: { ...res.data.平滑版 },
        };
        setTotalData(data);
      }
    });

    flexibleAggregation({ ...newReq, param: JSON.stringify(newReq.param) })
      .then((res: any) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          if (res.data) {
            const { data } = res.data;
            const { tableTreeData, exportData } = buildDimensionTableData(
              tileColumn.current,
              data,
              req.point,
            );
            const { filterOption, chartsArr, valIndex } = buildDimensionChartData(
              tableTreeData,
              req.order,
            );
            allTableTreeData.current = tableTreeData;
            tableExportData.current = exportData;
            setCurrentChartsArr(chartsArr);
            setChartFilterValus(valIndex);
            setChartFilterOptions(filterOption);
            setDataSource(tableTreeData);
          } else {
            setDataSource([]);
            setChartFilterValus([]);
            setCurrentChartsArr([]);
            setChartFilterOptions([]);
            tableExportData.current = [];
            allTableTreeData.current = [];
          }

          setLoading(false);
        } else {
          message.error(res.message);
          setLoading(false);
        }
      })
      .catch(() => {
        setLoading(false);
      });
  };

  const onSearch = (value: any) => {
    setReq(value);
  };

  const onReset = (value: any) => {
    const item = _.find(province, (n: ProvinceType) => n.value === value.marketId);
    if (item) {
      setCurrentProvinceInfo(item);
    }
    setReq(value);
  };

  const changeDimensionOptions = (valIndex: buildDimensionChartDataType['valIndex']) => {
    const lastNode = findNodeByIndexPath(allTableTreeData.current, valIndex);
    setChartFilterValus(valIndex);
    if (lastNode && lastNode.children) {
      setCurrentChartsArr(lastNode.children);
    }
  };

  const exportData = () => {
    const params = {
      multiHeader: exportHeader,
      header: header,
      data: tableExportData.current,
      merges: exportMerges,
      filename: `ai策略复盘${req.time[0].format('YYYYMMDD')}-${req.time[1].format('YYYYMMDD')}`,
    };
    export_json_to_excel(params);
  };

  useEffect(() => {
    setLoading(true);
    tileColumn.current = tileTbaleColumn(columns());
    init()
      .then((arr) => {
        const [res1, res2] = arr;

        if (res1.statusCode === HttpCode.SUCCESS && res2.statusCode === HttpCode.SUCCESS) {
          const { arr, defaultValue } = buildDictionaryStatusData(res2.data);
          const dValues = {
            issueStatus: defaultValue,
            algorithm: undefined,
          };
          const newAlgorithmList = res1.data.map((v: any) => {
            return {
              ...v,
              label: v.meaning,
              value: v.name,
            };
          });

          dValues.algorithm = newAlgorithmList[0].name;
          setAlgorithmList(newAlgorithmList);
          setDictionaryStatus(arr);
          setDefaultValues({
            ...dValues,
          });
          setReq({
            ...dValues,
          });
        }
      })
      .catch((err) => {
        setLoading(false);
      });
  }, []);

  useEffect(() => {
    if (req && req.stationIdList.length > 0 && req.issueStatus && req.regionCode) {
      query();
    }
  }, [req]);

  const pipeline = useTablePipeline()
    .input({ dataSource, columns: columns() })
    .primaryKey('id')
    .use(features.treeMode({ openKeys, onChangeOpenKeys: setOpenKeys }))
    .use(
      features.sort({
        mode: 'single',
        sorts: tableSorts,
        highlightColumnWhenActive: true,
        keepDataSource: true,

        onChangeSorts: (obj) => {
          if (obj && obj.length > 0) {
            if (!Array.isArray(dataSource) || dataSource.length <= 1) return;
            const [first, ...rest] = dataSource;
            const sorted = _.orderBy(
              rest,
              [(item: any) => Number(item[obj[0].code])],
              [obj[0].order],
            );
            setDataSource([first, ...sorted]);
            setTableSorts(obj);
          } else {
            setDataSource(allTableTreeData.current);
            setTableSorts([]);
          }
        },
      }),
    );

  return (
    <div className="ai-strategy-review">
      <TjHeader
        left={
          <TjFilter
            form={form}
            defaultValues={defaultValues}
            loading={loading}
            onSearch={onSearch}
            onReset={onReset}
            items={[
              {
                name: 'marketId',
                render: (
                  <Select
                    options={province}
                    style={{ width: 180 }}
                    loading={initLoading}
                    onChange={changeMarketId}
                    allowClear={false}
                  />
                ),
              },
              {
                name: 'stationIdList',
                render: (
                  <TjMarketingUnit treeData={treeData} marketId={currentProvinceInfo?.value} />
                ),
              },
              // {
              //   name: 'time',
              //   render: <RangePicker allowClear={false} />,
              // },
              // {
              //   name: 'algorithm',
              //   render: (
              //     <Select
              //       options={algorithmList}
              //       style={{ width: 180 }}
              //       loading={initLoading}
              //       allowClear={false}
              //     />
              //   ),
              // },
              // {
              //   name: 'issueStatus',
              //   render: (
              //     <Select options={dictionaryStatus} allowClear={false} loading={initLoading} />
              //   ),
              // },
              // {
              //   name: 'point',
              //   render: (
              //     <TjSlideSelect
              //       items={[
              //         { label: '24', value: '24' },
              //         { label: '96', value: '96' },
              //       ]}
              //     />
              //   ),
              // },
              // {
              //   name: 'tag',
              //   render: (
              //     <TjSlideSelect
              //       items={[
              //         { label: '测算数据', value: '1' },
              //         { label: '结算数据', value: '2' },
              //       ]}
              //     />
              //   ),
              // },
            ]}
          />
        }
        right={
          <>
            <Button
              type="link"
              onClick={exportData}
              loading={loading}
              disabled={dataSource.length === 0}
            >
              导出
            </Button>
          </>
        }
      />
      <BoardContent data={totalData} strategyType={req.strategyType} />
      <TjCollapse
        leftContent={
          <div className="ai-strategy-review-left">
            <Tabs
              activeKey={req.strategyType}
              className="tab"
              onChange={(val) => setReq({ strategyType: val })}
            >
              <Tabs.TabPane tab="策略版" key="1" />
              <Tabs.TabPane tab="平滑版" key="2" />
            </Tabs>
            <TjDimension
              value={dimensionVal}
              options={orderOptions}
              onChange={(order: any[]) => setDimensionVal(order)}
              onPoly={aggregation}
            />
            <div className="table-box">
              <TjTable {...pipeline.getProps()} isLoading={loading} />
            </div>
          </div>
        }
        rightContent={
          <div className="ai-strategy-review-right">
            {dataSource && dataSource.length > 0 ? (
              <>
                <TjDimensionOptions
                  listVal={chartFilterValus}
                  filterOptions={chartFilterOptions}
                  changeDimensionOptions={changeDimensionOptions}
                  loading={loading}
                />
                <div className="charts-list">
                  <DimensionCharts
                    name="偏差电费组成"
                    unit="元"
                    currentChartsArr={currentChartsArr}
                    showChartObj={chartsShowValueConfig.charts1}
                    loading={loading}
                  />
                  <DimensionCharts
                    name="综合扣费收入"
                    unit="元"
                    currentChartsArr={currentChartsArr}
                    showChartObj={chartsShowValueConfig.charts2}
                    loading={loading}
                  />
                  <DimensionCharts
                    name="综合扣费电价"
                    unit="元/MWh"
                    currentChartsArr={currentChartsArr}
                    showChartObj={chartsShowValueConfig.charts3}
                    loading={loading}
                  />
                </div>
              </>
            ) : (
              <TRDefault type={'empty'} />
            )}
          </div>
        }
      />
    </div>
  );
};

interface IAIStrategyReviewProps {
  menuCode?: string;
}

export default connect(({ global }: any) => ({
  menuCode: global.configure.menuCode,
}))(AIStrategyReview);
